<?php

defined('SYSPATH') OR die('No direct access allowed.');

class Stok_Controller extends Controller {

    public function __construct() {
        parent::__construct();
        $this->stok_model = new Stok_Model;
    }

    public function index() {        
        if(!parent::_authenticate()) {
			return;
		}
		parent::_loadContent("Stok", 'stok_content');
		$this->view->content->stoks = $this->stok_model;
		if(!empty($_POST['new_stock_submit'])) {//jika ada variabel post new_stock
			$this->validation = new Validation($_POST);
			$this->validation->add_rules('nama','required','length[1,32]');			
			$this->validation->add_rules('unit','required','standard_text');
			
			$this->validation->add_callbacks('nama',array($this,'_nama_check'));			
			if($this->validation->validate()) {
				$this->stok_model->insert_stok(array('nama' => $this->input->post('nama'), 'unit' => $this->input->post('unit')));
			}else{
				$this->view->content->errors = $this->validation->errors('stok_error');				
			}        
		}
		else if(!empty($_POST['inc_stock_submit'])) {//jika ada variabel post inc_stock
			$this->validation = new Validation($_POST);
			$this->validation->add_rules('item','required');
			$this->validation->add_rules('quantity','required','numeric');
			$this->validation->add_rules('harga_beli','required','numeric');
			
			$this->validation->add_callbacks('item',array($this,'_no_item_check'));
			$this->validation->add_callbacks('quantity',array($this,'_quantity_check'));			
			$this->validation->add_callbacks('harga_beli',array($this,'_harga_beli_check'));
			if($this->validation->validate()) {
				$this->view->content->test = $this->stok_model->increase_stok($this->input->post('item'),$this->input->post('quantity'),date("Y-m-d"),$this->input->post('harga_beli'));
			}else{
				$this->view->content->errors = $this->validation->errors('stok_error');
			}
		}
        $this->view->render(TRUE);
    }

	public function _nama_check(Validation $post) {
		if(array_key_exists('nama',$post->errors())) {
			return ;
		}
		if ($this->stok_model->check_already_exist_stock($post->nama)) {
			$post->add_error('nama', '_nama_check');
		}
	}
	
	public function _harga_beli_check(Validation $post) {
		if(array_key_exists('harga_beli',$post->errors())) {
			return;
		}
		if(intval($post->harga_beli)<0) {//jika negatif
			$post->add_error('harga_beli','_positive_numeric_check');
		}
	}
	
	public function _no_item_check(Validation $post) {
		if(array_key_exists('item',$post->errors())) {
			return ;
		}
		if (!$this->stok_model->check_already_exist_stock($post->item)) {
			$post->add_error('item', 'no_item');
		}
	}
	
	public function _quantity_check(Validation $post) {
		if(array_key_exists('quantity',$post->errors())) {
			return;
		}
		if(intval($post->quantity)<0) {
			$post->add_error('quantity','_positive_numeric_quantity_check');
		}
	}
}